<template>
  <BaseDialog :title="title" :width="dialogWidth" :visible="dialogVisible" @close="closeDialog"
    @confirm="confirmDialog">
    <template #content>
      <el-form ref="ruleFormRef" :model="formData" :rules="rules" label-suffix=" :">
        <el-form-item label="上级组织架构" prop="parentDepartmentId">
          <el-tree-select v-model="formData.parentDepartmentId" :data="organizeData" filterable check-strictly />
        </el-form-item>
        <el-form-item label="组织架构名称" prop="departmentName">
          <BInput v-model="formData.departmentName" placeholder="请输入" />
        </el-form-item>
      </el-form>
    </template>
  </BaseDialog>
</template>

<script setup lang="ts">
import { defineProps, defineEmits, ref, watch, onMounted, reactive } from 'vue';
import BaseDialog from '@/components/Dialog/BaseDialog.vue';
import { BInput } from '@/components/BaseComponents';
import { addOrganize, getOrganicTree } from '@/api/modules/organize';
import { ElMessage, FormInstance } from 'element-plus';


const dialogWidth = ref('600px')

const props = defineProps<{
  title: string;
  dialogVisible: boolean;
  treeFilterData: any;
}>();

const rules = reactive({

});

interface TreeNode {
  id: number;
  parentDepartmentId: number;
  departmentName: string;
  departmentType: number;
  children?: TreeNode[];
}

interface TreeSelectNode {
  value: number;
  label: string;
  children?: TreeSelectNode[];
}

//转换为树形结构
const convertToTreeSelectData = (data: TreeNode[]): TreeSelectNode[] => {
  return data.map(node => {
    const treeSelectNode: TreeSelectNode = {
      value: node.id,
      label: node.departmentName,
      children: node.children ? convertToTreeSelectData(node.children) : undefined
    };
    return treeSelectNode;
  });
}

//将数据转换成选择树结构
const organizeData = ref<any>()
watch(() => props.treeFilterData, (newValue) => {
  if (newValue) {
    organizeData.value = convertToTreeSelectData(newValue);
  }
}, { immediate: true })



const formData = ref({
  parentDepartmentId: undefined,
  departmentName: '',
})

const emits = defineEmits<{
  (event: 'close'): void;
  (event: 'confirm'): void;
}>();

const closeDialog = () => {
  emits('close');
};

const ruleFormRef = ref<FormInstance>();
const confirmDialog = async () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      await addOrganize(formData.value).then(() => {
        emits('confirm');
        ElMessage.success('新增组织架构成功');
      }).catch((error) => {
        ElMessage.error('新增组织架构失败');
      })

    } catch (error) {
      console.log(error);
    }
  });
};
</script>

<style scoped lang="scss">
.leave-dialog-content {
  padding: 20px;
}

.dialog-footer {
  text-align: center;
}
</style>
